package com.ruicar.afs.cloud.finance.mq.receiver.basic.processor;

import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.ruicar.afs.cloud.bizcommon.voucher.mq.sender.VoucherFlowSender;
import com.ruicar.afs.cloud.common.modules.contract.enums.*;
import com.ruicar.afs.cloud.common.modules.dto.mq.voucher.VoucherFlowInfoDto;
import com.ruicar.afs.cloud.common.modules.enums.BusinessType;
import com.ruicar.afs.cloud.common.mq.finance.debit.dto.ReceiptHandleCompleteDto;
import com.ruicar.afs.cloud.common.mq.finance.debit.dto.ReceiptHandleCompletePackageDto;
import com.ruicar.afs.cloud.common.mq.finance.debit.dto.ReceiptHandleDetailDto;
import com.ruicar.afs.cloud.common.mq.rabbit.listener.AfsMqBizProcessor;
import com.ruicar.afs.cloud.common.mq.rabbit.message.AfsTransEntity;
import com.ruicar.afs.cloud.common.mq.rabbit.message.MqTransCode;
import com.ruicar.afs.cloud.finance.common.entity.*;
import com.ruicar.afs.cloud.finance.common.service.*;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;
import java.util.Calendar;
import java.util.Date;
import java.util.List;

/**
 * <p>Description: </p>
 *
 * @author ZC.GUO
 * @version 1.0
 * @date create on 2020-07-04 17:22
 */
@AllArgsConstructor
@Slf4j
@Component
@ConditionalOnProperty(prefix = "com.ruicar.afs.cloud.mq.rabbit", name = "enable")
public class ReceiptHandleCompleteProcess implements AfsMqBizProcessor<ReceiptHandleCompletePackageDto> {

    private final FinanceVirtualAccountService financeVirtualAccountService;
    private final FinanceCustUnusedFundsService financeCustUnusedFundsService;
    private final FinanceUnusedFundsHistoryService financeUnusedFundsHistoryService;
    private final FinanceTransLineService financeTransLineService;
    private final FinanceReceiptOperateService financeReceiptOperateService;
    private final FinanceOperateDetailService financeOperateDetailService;
    private final VoucherFlowSender voucherFlowSender;

    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean processMessage(ReceiptHandleCompletePackageDto entity) throws Exception {
        return this.transData(entity);
    }

    @Override
    public MqTransCode getCode() {
        return MqTransCode.AFS_CONTRACT_BASIC_FINANCE_CONTRACT_RECEIPTHANDLE_COMPLETE;
    }

    private boolean transData(ReceiptHandleCompletePackageDto entity) {
        if (entity != null && entity.getReceiptHandleCompleteList().size() > 0) {
            for (ReceiptHandleCompleteDto receiptHandleCompleteDto : entity.getReceiptHandleCompleteList()) {
                this.handleCustUnusedFunds(receiptHandleCompleteDto,entity.getOperator());
            }
        }
        return true;
    }

    private void handleCustUnusedFunds(ReceiptHandleCompleteDto receiptHandleCompleteDto,String operator) {
        FinanceCustUnusedFunds financeCustUnusedFunds = financeCustUnusedFundsService.getOne(Wrappers.<FinanceCustUnusedFunds>query().lambda()
                .eq(FinanceCustUnusedFunds::getFundId, receiptHandleCompleteDto.getReceiptId())
                .eq(FinanceCustUnusedFunds::getStatus, UnusedFundsStatusEnums.locked)
        );
        if (financeCustUnusedFunds != null) {

            /**  客户虚拟账户信息更新 by ZC.GUO  **/
            FinanceVirtualAccount financeVirtualAccount = financeVirtualAccountService.getOne(Wrappers.<FinanceVirtualAccount>query().lambda()
                    .eq(FinanceVirtualAccount::getId, financeCustUnusedFunds.getAccountId())
            );

            /**  账务余额分配流水 by ZC.GUO  **/
            FinanceUnusedFundsHistory financeUnusedFundsHistory = new FinanceUnusedFundsHistory();
            financeUnusedFundsHistory.setAccountId(financeVirtualAccount.getId());
            financeUnusedFundsHistory.setContractNo(financeCustUnusedFunds.getContractNo());
            financeUnusedFundsHistory.setFundsType(FundLineEnum.handle);
            financeUnusedFundsHistory.setFundId(receiptHandleCompleteDto.getReceiptId());
            financeUnusedFundsHistory.setAmount(BigDecimal.ZERO.subtract(receiptHandleCompleteDto.getHandleAmount()));
            financeUnusedFundsHistoryService.save(financeUnusedFundsHistory);

            /**  当前待分配款项信息更新 by ZC.GUO  **/
            if (receiptHandleCompleteDto.getUnusedAmount().compareTo(BigDecimal.ZERO) <= 0) {
                financeVirtualAccountService.updateWhenDistribution(financeVirtualAccount, financeCustUnusedFunds.getAmount());
                financeCustUnusedFundsService.removeById(financeCustUnusedFunds.getId());
            } else {
                financeVirtualAccountService.updateWhenDistribution(financeVirtualAccount, receiptHandleCompleteDto.getHandleAmount());
                financeCustUnusedFundsService.updateWhenDistribution(financeCustUnusedFunds, financeCustUnusedFunds.getAmount().subtract(receiptHandleCompleteDto.getHandleAmount()));
            }

            /**  业务操作记录 by ZC.GUO  **/
            FinanceTransLine financeTransLine = new FinanceTransLine();
            financeTransLine.setCustNo(financeVirtualAccount.getCustNo());
            financeTransLine.setOperateType(TransOpreateTypeEnums.distribution);
            financeTransLine.setOperator(operator);
            financeTransLine.setOperateResult(ReturnCodeEnum.success);
            financeTransLine.setOperateTime(Calendar.getInstance().getTime());
            financeTransLineService.save(financeTransLine);

            /**  来款操作记录 by ZC.GUO  **/
            FinanceReceiptOperate financeReceiptOperate = new FinanceReceiptOperate();
            financeReceiptOperate.setTransId(financeTransLine.getId());
            financeReceiptOperate.setFundsType(receiptHandleCompleteDto.getReceiptSourceType());
            financeReceiptOperate.setFundsId(receiptHandleCompleteDto.getReceiptId());
            financeReceiptOperate.setTime(Calendar.getInstance().getTime());
            financeReceiptOperate.setType(ReceiptOperateTypeEnums.distribution);
            financeReceiptOperate.setAmount(receiptHandleCompleteDto.getHandleAmount());
            financeReceiptOperateService.save(financeReceiptOperate);

            /**  来款操作明细 by ZC.GUO  **/
            List<ReceiptHandleDetailDto> receiptHandleDetailDtoList = receiptHandleCompleteDto.getReceiptHandleDetailList();

            if (receiptHandleDetailDtoList != null && receiptHandleDetailDtoList.size() > 0) {
                for (ReceiptHandleDetailDto receiptHandleDetailDto : receiptHandleDetailDtoList) {
                    FinanceOperateDetail financeOperateDetail = new FinanceOperateDetail();
                    financeOperateDetail.setAccountId(financeVirtualAccount.getId());
                    financeOperateDetail.setOperateId(financeReceiptOperate.getId());
                    financeOperateDetail.setFeeType(receiptHandleDetailDto.getFeeTypeEnum());
                    financeOperateDetail.setFeeSourceTable(receiptHandleDetailDto.getFeeSourceTable());
                    financeOperateDetail.setFeeId(receiptHandleDetailDto.getFeeId());
                    financeOperateDetail.setReceiptDetailId(receiptHandleDetailDto.getReceiptDetailId());
                    financeOperateDetail.setAmount(receiptHandleDetailDto.getAmount());
                    financeOperateDetail.setPayAccount(receiptHandleCompleteDto.getSourceAccount());
                    financeOperateDetail.setReceiptAccount(receiptHandleCompleteDto.getCreditAccount());
                    financeOperateDetailService.save(financeOperateDetail);
                }
            }
            //凭证流水信息推送
            VoucherFlowInfoDto voucherFlowInfoDto = new VoucherFlowInfoDto();
            voucherFlowInfoDto.setTransNo(String.valueOf(financeReceiptOperate.getId()));
            voucherFlowInfoDto.setDealerName(receiptHandleCompleteDto.getDealerName());
            voucherFlowInfoDto.setBuriedPointNo(receiptHandleCompleteDto.getBuriedPointNo());
            voucherFlowInfoDto.setFinancialProducts(receiptHandleCompleteDto.getFinancialProducts());
            voucherFlowInfoDto.setContractNo(receiptHandleCompleteDto.getContractNo());
            voucherFlowInfoDto.setKeepAccountDate(new Date());
            if(BusinessTypeEnum.newCar.equals(receiptHandleCompleteDto.getBusinessType())){
               voucherFlowInfoDto.setBusinessType(BusinessType.NEW_CAR);
            } else if (BusinessTypeEnum.oldCar.equals(receiptHandleCompleteDto.getBusinessType())) {//新车
                voucherFlowInfoDto.setBusinessType(BusinessType.OLD_CAR);
            } else {
                log.error("业务类型:{},暂不支持！",receiptHandleCompleteDto.getBusinessType());
//                Assert.isTrue(false, MessageFormat.format("业务类型:{0},暂不支持！", receiptHandleCompleteDto.getBusinessType()));
            }
            AfsTransEntity<VoucherFlowInfoDto> entity = new AfsTransEntity<>();
            entity.setData(voucherFlowInfoDto);
            entity.setTransCode(MqTransCode.AFS_VOUCHER_FLOW_PUSH);
            voucherFlowSender.sendVoucherFlowToAccount(entity);
        }

    }
}
